package mapper

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	context2 "golang.org/x/net/context"
	"ksd-social-api/commons/page"
	"ksd-social-api/modules/user/model"
	"ksd-social-api/modules/user/model/context"
	"time"
)

type AdminUserMapper struct {
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存用户
 */
func (service *AdminUserMapper) SaveUpdateUser(user model.User) *model.User {
	db := orm.NewOrm()
	if user.Id > 0 {
		_, _ = db.Update(&user)
		return &user
	} else {
		_, _ = db.Insert(&user)
		return &user
	}
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户id查询用户明细
 */
func (mapper *AdminUserMapper) GetUserByID(id uint64, systemId uint64) *model.User {
	// 创建orm对象
	mysql := orm.NewOrm()
	var user model.User
	err := mysql.Raw("select * from xk_user where id = ? and system_id = ?").SetArgs(id, systemId).QueryRow(&user)
	if err != nil {
		return nil
	}
	return &user
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc 修改手机
 */
func (mapper *AdminUserMapper) UpdateTelephone(userId uint64, systemId uint64, telephone string) (flag bool, err error) {
	// 1: 获取链接
	db := orm.NewOrm()
	// 2: 开始执行修改密码的sql语句
	exec, _ := db.Raw("UPDATE xk_user SET telephone = ? , update_time = now() WHERE id = ?  and system_id = ?").SetArgs(telephone, userId, systemId).Exec()
	affected, err := exec.RowsAffected()
	if err != nil {
		return false, err
	}
	return affected > 0, nil
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc 修改手机
 */
func (mapper *AdminUserMapper) UpdateAdminTelephone(userId uint64, systemId uint64, telephone string) (flag bool, err error) {
	// 1: 获取链接
	db := orm.NewOrm()
	// 2: 开始执行修改密码的sql语句
	exec, _ := db.Raw("UPDATE xk_user SET telephone = ? ,account = ? , update_time = now() WHERE id = ?  and system_id = ?").SetArgs(telephone, telephone, userId, systemId).Exec()
	affected, err := exec.RowsAffected()
	if err != nil {
		return false, err
	}
	return affected > 0, nil
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc 修改密码
 */
func (mapper *AdminUserMapper) UpdatePwd(userId uint64, systemId uint64, slat string, newPwd string) (flag bool, err error) {
	// 1: 获取链接
	db := orm.NewOrm()
	// 2: 开始执行修改密码的sql语句
	exec, _ := db.Raw("UPDATE xk_user SET password = ? , slat = ? , update_time = now() WHERE id = ? and system_id = ?").SetArgs(newPwd, slat, userId, systemId).Exec()
	affected, err := exec.RowsAffected()
	if err != nil {
		return false, err
	}
	return affected > 0, nil
}

/**
 * @author feige
 * @date 2023-10-12
 * @version 1.0
 * @desc 查询小册分页
 */
func (mapper *AdminUserMapper) FindUserListAndPage(ctx context.UserSearchContext) (p *page.Page) {
	// 1：准备容器对象，开始装载数据库数据
	noteList := []model.User{}
	// 2：创建orm对象
	mysql := orm.NewOrm()
	cond := orm.NewCondition()
	// 3: 开始执行sql查询
	qs := mysql.QueryTable("xk_user")
	// 4: 设定两个条件
	cond = cond.
		And("is_deleted", 0).
		And("system_id", ctx.SystemId)
	// 5 : 判断分类是否传递如果不是""或者不是0就开始拼接条件
	if ctx.VipFlag > -1 {
		cond = cond.And("vip_flag", ctx.VipFlag)
	}
	if ctx.Forbidden > -1 {
		cond = cond.And("forbidden", ctx.Forbidden)
	}
	if ctx.TeacherFlag > -1 {
		cond = cond.And("teacher_flag", ctx.TeacherFlag)
	}
	if ctx.AuthorFlag > 0 {
		cond = cond.And("author_flag", ctx.AuthorFlag)
	}
	if len(ctx.Role) > 0 {
		cond = cond.And("role", ctx.Role)
	}
	if len(ctx.Uuid) > 0 {
		cond = cond.And("uuid", ctx.Uuid)
	}
	// 如果用户输入的搜索关键词
	if len(ctx.Keyword) > 0 {
		cond1 := orm.NewCondition()
		cond1 = cond1.Or("telephone__icontains", ctx.Keyword).
			Or("username__icontains", ctx.Keyword).
			Or("nickname__icontains", ctx.Keyword)
		cond = cond.AndCond(cond1)
	}

	// 6：执行count查询
	total, err1 := qs.SetCond(cond).Count()
	if err1 != nil {
		return nil
	}
	// 4: 重新换算分页和规则
	page := p.Page(ctx.PageNo, ctx.PageSize, total)
	// 5: 执行sql---count(1)---获得具体数据  10 0/ 10 10 / 10  20/  10 30
	querySeter := qs.SetCond(cond)
	querySeter = querySeter.OrderBy("-create_time")
	_, err2 := querySeter.Limit(page.PageSize, page.CurrentPage).All(&noteList,
		"id",
		"slat",
		"username",
		"nickname",
		"telephone",
		"address",
		"password",
		"sign",
		"bg_img",
		"birth_day",
		"avatar",
		"male",
		"open_id",
		"is_deleted",
		"forbidden",
		"author_flag",
		"uuid",
		"bbs_num",
		"course_num",
		"fans_num",
		"gzs_num",
		"vip_flag",
		"vip_time",
		"income",
		"province",
		"city",
		"job",
		"realname",
		"idcard",
		"idcardimgf",
		"idcardimgc",
		"alipaycode",
		"weixincode",
		"bankcode",
		"bankimg",
		"bankaddr",
		"coin",
		"system_id",
		"create_time",
		"update_time",
		"system_name",
		"status",
		"teacher_flag",
		"role",
		"intro",
		"account",
	)
	// 6：把查询的数据放入到分页的records字段，准备返回
	page.Records = noteList
	// 7: 如果没有找到直接返回
	if err2 != nil {
		return nil
	}
	return page
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存用户购买VIP信息
 */
func (mapper *AdminUserMapper) SaveUserBuyVip(userBuyVip model.UserBuyVip) bool {
	// 创建orm对象
	err := orm.NewOrm().DoTx(func(ctx context2.Context, txOrm orm.TxOrmer) (err error) {
		// 保存用户课程订单
		_, err = txOrm.Insert(&userBuyVip)
		// 用户升级VIP
		userVip := userVipMapper.GetUserVipDetail(userBuyVip.VipId, userBuyVip.SystemId)
		if nil != userVip {
			// 会员卡类型: 1天卡 2 周卡 3月卡 4 季度 5 年卡 6 SVIP
			// 开始查询用户的充值信息
			user := userMapper.GetUserByID(userBuyVip.UserId, userBuyVip.SystemId)
			if nil != user {
				// 获取用户会员时间
				vipTime := user.VipTime
				if vipTime.IsZero() {
					// 如果是nil，就获取当前时间
					vipTime = time.Now()
				}

				// 如果是初次或者每次身份叠加就修改身份的类型
				if user.VipFlag == 0 || userVip.VipType >= user.VipFlag {
					user.VipFlag = userVip.VipType
				}

				// 累加天数的VIP时间
				date := vipTime.AddDate(0, 0, userVip.VipDays)
				_, err = orm.NewOrm().Raw("UPDATE xk_user SET vip_flag = ?,vip_time = ? WHERE id = ? and system_id = ?").
					SetArgs(user.VipFlag, date, userBuyVip.UserId, userBuyVip.SystemId).
					Exec()
			}
		}

		return err
	})

	return err == nil
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户id查询用户明细
 */
func (mapper *AdminUserMapper) UpdateFieldById(id uint64, field string, value any, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw(fmt.Sprintf("update xk_user set %s='%v',update_time=now() where id = ? and system_id = ?", field, value)).SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户id查询用户明细
 */
func (mapper *AdminUserMapper) UpdateFieldByCodeId(id uint64, field string, value any, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw(fmt.Sprintf("update xk_user_vip_code set %s='%v',update_time=now() where id = ? and system_id = ?", field, value)).SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-12
 * @version 1.0
 * @desc 查询小册分页
 */
func (mapper *AdminUserMapper) FindUserCodePage(ctx context.CodeSearchContext) (p *page.Page) {
	// 1：准备容器对象，开始装载数据库数据
	userCodeList := []model.UserVipCode{}
	// 2：创建orm对象
	mysql := orm.NewOrm()
	cond := orm.NewCondition()
	// 3: 开始执行sql查询
	qs := mysql.QueryTable("xk_user_vip_code")
	// 4: 设定两个条件
	cond = cond.
		And("system_id", ctx.SystemId)
	if ctx.Mark > -1 {
		cond = cond.And("mark", ctx.Mark)
	}
	if len(ctx.Keyword) > 0 {
		cond = cond.And("code", ctx.Keyword)
	}
	// 5 : 判断分类是否传递如果不是""或者不是0就开始拼接条件
	total, err1 := qs.SetCond(cond).Count()
	if err1 != nil {
		return nil
	}
	// 4: 重新换算分页和规则
	page := p.Page(ctx.PageNo, ctx.PageSize, total)
	// 5: 执行sql---count(1)---获得具体数据  10 0/ 10 10 / 10  20/  10 30
	querySeter := qs.SetCond(cond)
	querySeter = querySeter.OrderBy("mark")
	_, err2 := querySeter.Limit(page.PageSize, page.CurrentPage).All(&userCodeList,
		"id",
		"opid",
		"code",
		"mark",
		"system_id",
		"system_name",
		"create_time",
		"update_time",
	)
	// 6：把查询的数据放入到分页的records字段，准备返回
	page.Records = userCodeList
	// 7: 如果没有找到直接返回
	if err2 != nil {
		return nil
	}
	return page
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存和修改兑换码
 */
func (service *AdminUserMapper) SaveUpdateUserCode(code model.UserVipCode) *model.UserVipCode {
	db := orm.NewOrm()
	if code.Id > 0 {
		_, _ = db.Update(&code)
		return &code
	} else {
		_, _ = db.Insert(&code)
		return &code
	}
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据id删除
 */
func (mapper *AdminUserMapper) DelById(id uint64, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw("delete from xk_user  where id = ? and system_id = ?").SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据id删除
 */
func (mapper *AdminUserMapper) DelCodeById(id uint64, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw("delete from xk_user_vip_code  where id = ? and system_id = ?").SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}
